package com.ai.enviro.module.system.dao.local;

import com.ai.enviro.module.system.dao.IotEnvStorage;
import com.ai.enviro.module.system.dao.dataobject.IotEnvDO;
import com.ai.enviro.module.system.dao.mysql.IotEnvDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;

@Repository
public class IotEnvDbStorage implements IotEnvStorage {
    public static final Integer DATA_ID = 1;

    @Autowired
    private IotEnvDao iotEnvDao;

    private BigDecimal convertValue(int value) {
        return new BigDecimal(value).divide(new BigDecimal(10));
    }

    @Override
    public void save(int temperature, int humidity) {
        IotEnvDO envDO = new IotEnvDO().setId(DATA_ID).setTemperature(convertValue(temperature)).setHumidity(convertValue(humidity))
                .setCreateTime(new Date()).setUpdateTime(new Date());
        boolean updated = iotEnvDao.updateById(envDO);
        if (!updated) {
            iotEnvDao.save(envDO);
        }
    }

    @Override
    public IotEnvDO getIotEnv() {
        IotEnvDO envDO = iotEnvDao.getById(DATA_ID);
        return envDO != null ? envDO : new IotEnvDO().setTemperature(BigDecimal.ZERO).setHumidity(BigDecimal.ZERO);
    }
}
